/**
 * 数据存取
 */
var fs = require("fs");

var lsn_plan_template = {
	className: String,
	point: String,
	teacher: String,
	teacherStatus: String,
	department: String,
	book: String,
	year: String,
	term: String,
	timeAndPosition: String,
	status: String,
	class: String,
	grade: String,
}

var lsn_pub_required_template = {
	className: String,
	point: String,
	teacher: String,
	teacherStatus: String,
	department: String,
	book: String,
	year: String,
	term: String,
	timeAndPosition: String,
	remark: String,
	class: String,
}

var lsn_pub_optional_template = {
	className: String,
	point: String,
	teacher: String,
	teacherStatus: String,
	department: String,
	book: String,
	year: String,
	term: String,
	timeAndPosition: String,
	kind: String,
}

function dataSet(name) {
	this._init(name);
}
dataSet.prototype = {
	_init: function(name) {
		this.data = [];
		this.setName = name || 'default';
	},
	save: function(json) {
		this.data.push(json);
	},
	length: function() {
		return this.data.length;
	},
	load: function() {
		var result = {};
		result[this.setName] = this.data;
		return JSON.stringify(result);
	},
	loadSql: function() {
		var value = [];
		this.data.forEach(function(el, index) {
			var sql_value = [];
			// for(var key in el){

			// 	sql_value.push("'" + el[key] + "'");
			// }

			for (var key in lsn_plan_template) {
				sql_value.push("'" + el[key].replace(/\'/g, "\\'") + "'");
			}

			value.push("(" + sql_value.join(",") + ")");
		});
		return "INSERT INTO `" + this.setName + "` VALUES " + value.join(",") + ";";
	},
	saveToFile: function(fileName) {
		fs.writeFile(fileName, this.load(), function(err) {
			if (err) {
				throw err;
			}
			console.log("file Saved !"); //文件被保存
		});
	},
	readFromFile: function(fileName, callback) {
		var that = this;
		fs.readFile(fileName, 'utf-8', function(err, data) {
			if (err) {
				console.log("can not read " + fileName);
			} else {
				var fileData = JSON.parse(data);
				var fileContent;
				for (var key in fileData) {
					that.setName = key;
					fileContent = fileData[key];
				}
				fileContent.forEach(function(el, index) {
					that.save(el);
				});
				if (callback) {
					callback(that);
				}
			}
		});
	},
	exportSql: function(fileName) {
		fs.writeFile(fileName, this.loadSql(), function(err) {
			if (err) {
				throw err;
			}
			console.log("sql Exported !"); //文件被保存
		});
	}
};

module.exports.dataSet = dataSet;
